import os
from datetime import datetime
import sys
from smbprotocol.connection import Connection
from smbprotocol.session import Session
from smbprotocol.exceptions import SMBAuthenticationError # Replace SMBConnectionError with SMBError

# 支持的图片格式（保持不变）
IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif'}
# 从环境变量获取HTTP服务器信息（用于局域网访问）
http_server = os.getenv("HTTP_SERVER", "192.168.31.228")  # 默认localhost（可改为局域网IP）
http_port = os.getenv("HTTP_PORT", "8010")            # 默认端口8000

def get_latest_images(folder_path, count=2):  # 修改：默认取2张
    # 优先使用SMB连接（通过环境变量判断）
    smb_server = os.getenv("SMB_SERVER")
    if smb_server:
        return get_smb_images(smb_server, count)
    else:
        return get_local_images(folder_path, count)

def get_local_images(folder_path, count=2):
    
    # 获取所有文件并筛选图片
    all_files = []
    for filename in os.listdir(folder_path):
        filepath = os.path.join(folder_path, filename)
        if os.path.isfile(filepath):
            ext = os.path.splitext(filename)[1].lower()
            if ext in IMAGE_EXTENSIONS:
                mtime = os.path.getmtime(filepath)
                http_filepath = f"http://{http_server}:{http_port}/{filename}"
                all_files.append((mtime, http_filepath, filename))
    all_files.sort(reverse=True, key=lambda x: x[0])
    return all_files[:count]

def get_smb_images(smb_server, count=2):
    """从SMB服务器获取最新图片"""
    # 从环境变量获取SMB连接参数
    smb_share = os.getenv("SMB_SHARE", "pictures")  # 共享名，默认"pictures"
    smb_user = os.getenv("SMB_USER")
    smb_pass = os.getenv("SMB_PASS")
    smb_path = os.getenv("SMB_PATH", "/")  # 共享内路径，默认根目录

    try:
        # 连接SMB服务器
        with Connection(remote_host=smb_server, port=445) as conn:
            conn.connect()
            session = Session(conn, smb_user, smb_pass)
            session.connect()

            # 列出共享目录下的文件
            tree = session.tree_connect(smb_share)
            file_list = tree.list_path(smb_path)

            # 从环境变量获取HTTP服务器信息（用于局域网访问）
            http_server = os.getenv("HTTP_SERVER", "0.0.0.0")  # 默认localhost（可改为局域网IP）
            http_port = os.getenv("HTTP_PORT", "8010")            # 默认端口8000
    
            # 筛选图片文件并排序
            images = []
            for file_info in file_list:
                filename = file_info.filename
                ext = os.path.splitext(filename)[1].lower()
                if ext in IMAGE_EXTENSIONS:
                    mtime = file_info.creation_time.timestamp()
                    # 改为HTTP URL格式（局域网可访问）
                    http_filepath = f"http://{http_server}:{http_port}/{filename}"
                    images.append((mtime, http_filepath, filename))  # 替换为HTTP路径

            images.sort(reverse=True, key=lambda x: x[0])
            return images[:count]

    except SMBAuthenticationError:
        raise ValueError("SMB认证失败：用户名/密码错误")

def generate_html(images, output_path):
    html_content = f"""
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="refresh" content="10">
        <title>最新2张图片展示</title>
        <style>
            body {{ font-family: Arial, sans-serif; margin: 20px; }}
            h1 {{ color: #333; text-align: center; }}
            .gallery {{ 
                display: grid; 
                grid-template-columns: 1fr 1fr;  /* 固定两列左右展示 */
                gap: 20px;  /* 调整图片间距 */
                padding: 20px;
            }}
            .img-container {{
                border: 1px solid #ddd;
                border-radius: 8px;
                overflow: auto;  /* 允许内容溢出时滚动（避免图片过大撑破容器） */
                box-shadow: 0 3px 2px rgba(0,0,0,0.1);
            }}
            .img-container img {{
                width: auto;  /* 取消强制宽度 */
                height: auto;  /* 取消强制高度 */
                max-width: 100%;  /* 最大宽度不超过容器 */
                max-height: 100%;  /* 限制最大高度（可根据需求调整） */
                object-fit: contain;  /* 保持图片比例填充 */
                cursor: pointer;
                transition: transform 0.3s;
            }}
            .img-container img:hover {{
                transform: scale(1.05);
            }}
            .img-info {{
                padding: 10px;
                text-align: center;
                background-color: #f9f9f9;
            }}
            /* 新增模态框样式 */
            .modal {{
                display: none;
                position: fixed;
                z-index: 999;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                overflow: auto;
                background-color: rgba(0,0,0,0.9);
            }}
            .modal-content {{
                margin: 5% auto;
                width: 90%;
                max-width: 1200px;
                display: flex;
                gap: 20px;
                justify-content: center;
            }}
            .modal-img {{
                max-height: 1900px;
                border: 3px solid #fff;
                border-radius: 5px;
            }}
            .close {{
                position: absolute;
                top: 15px;
                right: 35px;
                color: #f1f1f1;
                font-size: 40px;
                font-weight: bold;
                cursor: pointer;
            }}
        </style>
    </head>
    <body>
        <h1>最新2张图片（共{len(images)}张）</h1>
        <div class="gallery">
            {"".join([f'''
            <div class="img-container">
                <img src="{img[1]}" alt="{img[2]}" onclick="showImages('{img[1]}', {idx})">  <!-- 注意：src使用SMB路径 -->
                <div class="img-info">
                    {img[2]}
                </div>
            </div>
            ''' for idx, img in enumerate(images)])}
        </div>

        <!-- 新增模态框结构 -->
        <div id="imageModal" class="modal">
            <span class="close" onclick="closeModal()">&times;</span>
            <div class="modal-content">
                <img class="modal-img" id="currentImg">
                <img class="modal-img" id="nextImg">
            </div>
        </div>

        <script>
            function showImages(currentImgPath, currentIndex) {{
                const modal = document.getElementById('imageModal');
                const currentImg = document.getElementById('currentImg');
                const nextImg = document.getElementById('nextImg');
                
                // 显示当前图片
                currentImg.src = currentImgPath;
                
                // 获取下一张图片路径（循环显示）
                const images = {images};  // 注入图片列表数据
                const nextIndex = (currentIndex + 1) % images.length;
                nextImg.src = images[nextIndex][2];  // 取第3个元素（文件名）
                
                modal.style.display = "block";
            }}

            function closeModal() {{
                document.getElementById('imageModal').style.display = "none";
            }}

            // 点击模态框外区域关闭
            window.onclick = function(event) {{
                const modal = document.getElementById('imageModal');
                if (event.target === modal) {{
                    modal.style.display = "none";
                }}
            }}
        </script>
    </body>
    </html>
    """
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(html_content)

if __name__ == "__main__":
    # 若使用SMB，folder_path参数会被忽略
    current_folder = os.getcwd()
    output_file = os.path.join(current_folder, 'index.html')
    
    try:
        latest_images = get_latest_images(current_folder)
        if not latest_images:
            print("未找到图片文件（本地或SMB）")
        else:
            generate_html(latest_images, output_file)
            print(f"已生成图片展示页面：{output_file}")
    except Exception as e:
        print(f"错误：{str(e)}")